package com.atguigu.eduservice.service.impl;

import com.aiguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.vo.VideoInfoVo;
import com.atguigu.eduservice.feign.VodFeignService;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-09-24
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    /**
     * 远程调用
     */
    @Resource
    private VodFeignService vodFeignService;


    @Override
    public void saveEntity(VideoInfoVo videoInfoVo) {
        // 创建小节对象
        EduVideo eduVideo = new EduVideo();
        // copy对象
        BeanUtils.copyProperties(videoInfoVo, eduVideo);
        if (!this.save(eduVideo)) {
            throw new GuLiException(ResultCode.ERROR, "保存小结失败");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteEntityByCourseId(String courseId) {
        // 删除小节


        LambdaQueryWrapper<EduVideo> eduVideoWrapper = new LambdaQueryWrapper();
        eduVideoWrapper.eq(EduVideo::getCourseId, courseId).select(EduVideo::getVideoSourceId);


        // 删除视屏
        List<String> videoIds = new ArrayList<>();
        List<EduVideo> list = this.list(eduVideoWrapper);
        for (EduVideo eduVideo : list) {
            if(!StringUtils.isBlank(eduVideo.getVideoSourceId())){
                videoIds.add(eduVideo.getVideoSourceId());
            }
        }
        if(list.size() > 0){
            vodFeignService.deleteBatch(videoIds);
        }

        // 删除小节
        this.remove(eduVideoWrapper);

    }
}
